package com.zhengshang.third.wikeyun;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.utils.ServletUtils;
import com.zhengshang.common.utils.http.HttpUtils;
import com.zhengshang.common.utils.ip.IpUtils;
import com.zhengshang.common.utils.sign.Md5Utils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * 微客云工具类
 */
@Component
public class WikeyunUtils {

    /**
     * 应用Key
     */
    private static final String appKey = "1039440055";
    /**
     * 密钥
     */
    private static final String appSecret = "c3a5e81509a70624145fe2cb00651546";
    /**
     * 请求地址
     */
    private static final String baseUrl = "https://router.wikeyun.cn/rest";
    /**
     * 店铺Id
     */
    public static final String storeId = "4066";

    /**
     * 设置公共请求参数
     *
     * @return
     */
    private static TreeMap setCommonParams() {
        TreeMap<String, Object> params = new TreeMap<>();
        long nowTimeStamp = System.currentTimeMillis() / 1000L;
        params.put("app_key", appKey);
        params.put("format", "JSON");
        params.put("v", "1.0");
        params.put("timestamp", nowTimeStamp);
       /* params.put("client", IpUtils.getIpAddr(ServletUtils.getRequest()));*/
        return params;
    }


    /**
     * 获取签名
     *
     * @return
     */
    private String getSign(TreeMap<String, Object> params) {
        String asciiSort = getSignAsciiSort(params);
        String needMd5Str = appSecret + asciiSort + appSecret;
        System.out.println("签名排序：" + needMd5Str);
        String sign = Md5Utils.hash(needMd5Str).toUpperCase();
        System.out.println("sign:" + sign);
        return sign;
    }


    /**
     * 获取权益订单签名
     *
     * @return
     */
    public String getQuanYiOrderSign(String orderNo) {
        String needMd5Str = appKey + appSecret + orderNo;
        String sign = Md5Utils.hash(needMd5Str);
        System.out.println("sign:" + sign);
        return sign;
    }

    /**
     * 参数进行拼接
     *
     * @param params
     * @return
     */
    private String getAsciiSort(TreeMap<String, Object> params) {
        StringBuilder s1 = new StringBuilder();
        for (String key : params.keySet()) {
            s1.append(key).append("=").append(params.get(key)).append("&");
        }
        s1.deleteCharAt(s1.length() - 1);
        return s1.toString();
    }

    /**
     * 参数进行拼接
     *
     * @param params
     * @return
     */
    private String getSignAsciiSort(TreeMap<String, Object> params) {
        StringBuilder s1 = new StringBuilder();
        for (String key : params.keySet()) {
            String data = TypeUtils.castToString(params.get(key));
            s1.append(key).append(data);
        }
        return s1.toString();
    }

    /**
     * get方式请求接口
     *
     * @param params
     * @param url
     * @return
     */
    public String sendGetRequest(TreeMap<String, Object> params, String url) {
        TreeMap commonParams = setCommonParams();
        commonParams.putAll(params);
        String sign = getSign(commonParams);
        commonParams.put("sign", sign);
        String asciiSort = getAsciiSort(commonParams);
        String resultStr = HttpUtils.sendGet(baseUrl + url, asciiSort);
        return resultStr;
    }

    /**
     * psot方式请求接口
     *
     * @param params
     * @param url
     * @return
     */
    public String sendPostRequest(TreeMap<String, Object> params, String url) {
        TreeMap commonParams = setCommonParams();
        TreeMap<String, Object> allParams = new TreeMap<>();
        allParams.putAll(params);
        allParams.putAll(commonParams);
        String sign = getSign(allParams);
        commonParams.put("sign", sign);
        String asciiSort = getAsciiSort(commonParams);
        System.out.println("asciiSort:" + asciiSort);
        Map<String, Object> bodys = new HashMap<>();
        bodys.putAll(params);
        bodys.putAll(commonParams);
        HttpResponse httpResponse = HttpUtils.doPost(baseUrl + url, asciiSort, bodys);
        System.out.println(baseUrl + url);
        System.out.println(asciiSort);
        System.out.println(bodys);
        String result = null;
        try {
            result = EntityUtils.toString(httpResponse.getEntity());
            System.out.println("请求结果：" + result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 转换返回数据格式
     *
     * @param jsonObject
     * @return
     */
    public AjaxResult converAjaxResult(JSONObject jsonObject) {
        String code = jsonObject.getString("code");
        if ("0000".equals(code)) {
            Object data = jsonObject.get("data");
            return AjaxResult.success(data);
        } else {
            String msg = jsonObject.getString("msg");
            return AjaxResult.error(msg);
        }
    }
}
